<?php
/**
 * Created by PhpStorm.
 * User: 13095
 * Date: 2018/9/14
 * Time: 10:56
 */

namespace app\api\controller;


use app\api\validate\ValidateRole;
use app\common\controller\Api;
use think\Controller;
use think\Exception;
use think\Request;
use think\Session;

class Role extends Controller
{
    protected $data;
    protected $model;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->model = model('Role');
    }

    public function  lists()
    {
        $this->data['where'] = array();
        $this->data['field'] = 'id,role_name,role_on,role_status,parent_id,level,create_time';
        $this->data['order'] = 'level asc';
        $this->data['page'] = $_GET['page'];
        $this->data['limit'] = $_GET['limit'];
        $this->data['data'] = $this->model->lists($this->data);
        Api::returnJson('0', $this->data['data'], $this->model->where($this->data['where'])->count());
    }

    public function add()
    {
        if($this->request->isPost()){
            $this->data['data'] = $_POST;
            if($this->data['data']['parent_id'] == 0){
                $this->data['data']['level'] = 0;
            }else{
                $levelArray = explode('|',$this->data['data']['parent_id']);
                $this->data['data']['parent_id'] = $levelArray[0];
                $this->data['data']['level'] = $levelArray[1]+1;
            }
            $this->data['data']['role_on'] = json_encode($this->data['data']['role_on']);
            if($this->data['data']){
                $validateRole = new ValidateRole();
                if(!$validateRole->scene('add')->check($this->data['data'])){
                    $this->error($validateRole->getError());
                }
                try{
                    $res = $this->model->add($this->data['data']);
                    if($res === true){
                        Api::returnJson('200', [], '新增成功');
                    }
                    throw  new Exception($res);
                }catch (Exception $e)
                {
                    Api::returnJson('500', [], $e->getMessage());
                }
            }else{
                Api::returnJson('500', [], '数据不存在');
            }
        }
    }

    public function edit()
    {
        if($this->request->isPost()){
            $this->data['data'] = $_POST;
            if($this->data['data']['parent_id'] == 0){
                $this->data['data']['level'] = 0;
            }else{
                $levelArray = explode('|',$this->data['data']['parent_id']);
                $this->data['data']['parent_id'] = $levelArray[0];
                $this->data['data']['level'] = $levelArray[1]+1;
            }
            $this->data['where'] = array('id'=>$this->data['data']['ids']);
            $this->data['data']['role_on'] = json_encode($this->data['data']['role_on']);
            if($this->data['data']){
                $validateRole = new validateRole();
                if(!$validateRole->scene('edit')->check($this->data['data'])){
                    Api::returnJson('200', [], $validateRole->getError());
                }
                try{
                    $res = $this->model->edit($this->data);
                    if($res === true){
                        Api::returnJson('200', [], '编辑成功');
                    }
                    throw  new Exception($res);
                }catch (Exception $e)
                {
                    Api::returnJson('500', [], $e->getMessage());
                }
            }else{
                Api::returnJson('500', [], '数据不存在');
            }
        }
    }

    public function del($ids)
    {
        if(empty($ids)){
            Api::returnJson('500',[],lang('data empty'));
        }
        $res = $this->model->where(['id'=>$ids])->delete();
        if($res){
            Api::returnJson('200',[],lang('Operation is successful'));
        }
        Api::returnJson('500',[],lang('The operation failure'));
    }

    /**
     * 获取auth json 数据
     */
    public function auth_json($operation = false,$ids = 0)
    {
        try{
            $where['field'] = 'auth_name as title,id as value,parent_id';
            //获取所有数据
            $this->data['all'] = model('Auth')->lists($where);

            //判断操作类型
            if($operation){
                //获取拥有数据
                $where['field'] = 'id,role_name,role_on,parent_id,level';
                $where['where'] = array('id'=>$ids);
                $data['own'] = $this->model->getOneData($where);

                foreach ($this->data['all'] as $key=>$value)
                {
                    foreach (json_decode($data['own']['role_on'],true) as $key_=> $value_){
                        if($value_ == $value['value']){$this->data['all'][$key]['checked'] = 'true';
                        }
                    }
                }
                $this->data['relo']['name'] = $data['own']['role_name'];
                $this->data['relo']['id'] = $data['own']['id'];
                unset($this->data['own']);
            }
            if(is_array($this->data['all'])){
                $this->data['all'] = $this->list_to_tree($this->data['all']);
                Api::returnJson(200,$this->data,'');
            }
            throw new Exception($this->data['all']);
        }catch (Exception $e)
        {
            Api::returnJson(201,array(),$e->getMessage());
        }
    }

    /**
     * 遍历成无限分类数组
     */
    function list_to_tree($list, $pk = 'value', $pid = 'parent_id', $child = 'data', $root = 0, $operation = false)
    {
        $tree = array();// 创建Tree
        if (is_array($list)) {
            // 创建基于主键的数组引用
            $refer = array();
            foreach ($list as $key => $data) {
                $refer[$data[$pk]] =& $list[$key];
            }
            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId = $data[$pid];
                if ($root == $parentId) {//父类id
                    $tree[] =& $list[$key];
                    $list[$key][$child] = array();
                } else {
                    if (isset($refer[$parentId])) {
                        $parent =& $refer[$parentId];
                        $parent[$child][] =& $list[$key];
                        $list[$key][$child] = array();
                    }
                }
                unset($list[$key]['parent_id']);
            }
        }
        return $tree;
    }

}